package main

import (
    "os/exec"
    "log"
    "bytes"
)

type Command struct {
    Arg       []interface{}     /* Arguments */
    Fun         string
    Jid         string
    Ret         bool
    Serial      int
    Tgt       []string
    TgtType     string
    User        string
}

type Engine struct {
}

func NewEngine() *Engine {
    return &Engine{}
}

func (e *Engine) execute(m Minion, c Command) error {
    log.Printf("Execute %s with %s", c.Fun, c.Jid)
    if c.Fun == "test.ping" {
        log.Printf("Ping request")
        m.answer(c.Jid, "OK")
    } else if c.Fun == "cmd.run" {
        log.Printf("Execute system command `%s`", c.Arg)
        op := exec.Command("date")
        var outb, errb bytes.Buffer
        op.Stdout = &outb
        op.Stderr = &errb
        err := op.Run()
        if err != nil {
            return err
        }
        log.Printf("out:", outb.String(), "err:", errb.String())
        m.answer(c.Jid, outb.String())
    } else {
        // TODO - provide error ...
    }

    return nil
}

func NewCommand() Command {
    return Command{}
}

func (c *Command) SetJid(jid string) {
    c.Jid = jid
}

func (c *Command) SetFun(fun string) {
    c.Fun = fun
}
